package com.ls.mysql.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.mysql.entity.YzStatus;
import com.ls.mysql.entity.YzUsers;
import com.ls.mysql.service.UserService;
import com.ls.mysql.util.JSONFilter;
import com.ls.mysql.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

@Controller
public class UserController {

    private Random random = new Random();

    @Autowired
    private UserService us;

    //用户登录
    @RequestMapping(value = "user/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject select(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, Model model) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -2;
        String msg = "登陆失败,验证码错误";
        // 用户登录的验证码
        String checkCode = request.getParameter("checkcode");
        // session内存留的校验码
        String session_checkcode = (String) request.getSession().getAttribute("checkCode");
        if (session_checkcode.equals(checkCode)) {
            statusCode = -1;
            msg = "登陆失败,请输入正确的用户名和密码";
            YzUsers u = us.UserLogin(username, password);
            if (u != null) {
                statusCode = 1;
                msg = "登陆成功";
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                json.put("log", df.format(new Date()) + "用户：" + username + "登陆成功");
                request.getSession().setAttribute("user", u);
            }
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //用户登录无验证码POST
    @RequestMapping(value = "user/login2", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject selectGET(@RequestParam("username") String username, @RequestParam("password") String password/*Model model*/, HttpServletRequest request) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "登陆失败";
        YzUsers u = us.UserLogin(username, password);
        if (u != null) {
            statusCode = 1;
            msg = "登陆成功";
            request.getSession().setAttribute("user", u);
//            model.addAttribute("user", u);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        json.put("log:", df.format(new Date()) + "用户：" + username + "登陆成功");
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //用户注册
    @RequestMapping(value = "user/register", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject add(HttpServletRequest request) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "注册失败";
        //取值
        String uname = (request.getParameter("username") == null || request.getParameter("username") == "") ? null : request.getParameter("username");
        int countIs = us.isExistUsername(uname);
        if (countIs > 0) {
            msg = "该用户名已被注册";
            json.put("statusCode", statusCode);
            json.put("msg", msg);
            return json;
        }
        String password = (request.getParameter("password") == null || request.getParameter("password") == "") ? null : request.getParameter("password");
        if (uname == null || password == null) {
            msg = "用户名或密码不允许为空";
        } else {
            String name = (request.getParameter("name") == null || request.getParameter("name") == "") ? null : request.getParameter("name");
            String mobile = (request.getParameter("mobile") == null || request.getParameter("mobile") == "") ? null : request.getParameter("mobile");
            //年龄若空值则不进行转化，否则Integer转化空值会报空指针异常
            boolean aGe = false;
            int age = 0;
            try {
                String ageSTR = (request.getParameter("age") == null || request.getParameter("age") == "") ? null : request.getParameter("age");
                if (ageSTR != null) age = Integer.parseInt(request.getParameter("age"));
            } catch (Exception e) {
                msg = "年龄字段应为纯数字";
                json.put("statusCode", statusCode);
                json.put("msg", msg);
                return json;
            }
            String address = (request.getParameter("address") == null || request.getParameter("address") == "") ? null : request.getParameter("address");
            String qq = (request.getParameter("qq") == null || request.getParameter("qq") == "") ? null : request.getParameter("qq");
            String wechat = (request.getParameter("wechat") == null || request.getParameter("wechat") == "") ? null : request.getParameter("wechat");
            String email = (request.getParameter("email") == null || request.getParameter("email") == "") ? null : request.getParameter("email");
            String sex = (request.getParameter("sex") == null || request.getParameter("sex") == "") ? null : request.getParameter("sex");
            //用户数组与年龄一样需要判空否则如下的for循环会报空指针错误
            String[] aihao = request.getParameterValues("aihao") == null ? null : request.getParameterValues("aihao");
            String Aihao = "";
            if (aihao != null) {
                for (String s : aihao) {
                    Aihao += s + ",";
                }
                Aihao = Aihao.substring(0, Aihao.length() - 1);
            }
            String jiguan = (request.getParameter("jiguan") == null || request.getParameter("jiguan") == "") ? null : request.getParameter("jiguan");
            //实体对象转存数据
            YzUsers u = new YzUsers();
            //  用户id程序生成
            String create_uid = "";
            while (true) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                int count = us.isExistUser(uuid);
                if (count == 0) {
                    create_uid = uuid;
                    break;
                }
            }
            if (!create_uid.equals("")) {
                u.setId(create_uid);
                u.setUsername(uname);
                u.setRealname(name);
                u.setPassword(password);
                if (mobile != null) u.setMobile(mobile);
                if (aGe) u.setAge(age);
                ;
                if (address != null) u.setAddress(address);
                if (qq != null) u.setQq(qq);
                if (wechat != null) u.setWechat(wechat);
                if (email != null) u.setEmail(email);
                if (sex != null) u.setSex(sex);
                if (aihao != null) u.setHobby(Aihao);
                if (jiguan != null) u.setDerive(jiguan);
                //初始化用户身份
                YzStatus ys = new YzStatus();
                ys.setId(12);
                u.setYzStatus(ys);
                int AffectLine = us.UserRegister(u);
                if (AffectLine > 0) {
                    statusCode = 1;
                    msg = "注册成功";
                }
            }
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //检验用户名是否存在 redis or mysql
    @RequestMapping(value = "user/uniqueUsername", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject isExistUsername(@RequestParam("username") String username, HttpSession session) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "用户名已存在";
        int result = us.isExistUsername(username);
        if (result == 0) {
            statusCode = 1;
            msg = "此用户名可用";
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //修改用户
    @RequestMapping(value = "user/update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject updateUser(HttpServletRequest request) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "信息修改失败";
        //取值
        String user_id = (request.getParameter("user_id") == null || request.getParameter("user_id") == "") ? null : request.getParameter("user_id");
        String uname = (request.getParameter("username") == null || request.getParameter("username") == "") ? null : request.getParameter("username");
        String password = (request.getParameter("password") == null || request.getParameter("password") == "") ? null : request.getParameter("password");
        String name = (request.getParameter("name") == null || request.getParameter("name") == "") ? null : request.getParameter("name");
        String mobile = (request.getParameter("mobile") == null || request.getParameter("mobile") == "") ? null : request.getParameter("mobile");
        //年龄若空值则不进行转化，否则Integer转化空值会报空指针异常
        boolean aGe = false;
        int age = 0;
        try {
            String ageSTR = (request.getParameter("age") == null || request.getParameter("age") == "") ? null : request.getParameter("age");
            if (ageSTR != null) age = Integer.parseInt(request.getParameter("age"));
            aGe = true;
        } catch (Exception e) {
            msg = "芳龄字段应为纯数字";
            json.put("statusCode", statusCode);
            json.put("msg", msg);
            return json;
        }
        String address = (request.getParameter("address") == null || request.getParameter("address") == "") ? null : request.getParameter("address");
        String qq = (request.getParameter("qq") == null || request.getParameter("qq") == "") ? null : request.getParameter("qq");
        String wechat = (request.getParameter("wechat") == null || request.getParameter("wechat") == "") ? null : request.getParameter("wechat");
        String email = (request.getParameter("email") == null || request.getParameter("email") == "") ? null : request.getParameter("email");
        String sex = (request.getParameter("sex") == null || request.getParameter("sex") == "") ? null : request.getParameter("sex");
        String jiguan = (request.getParameter("jiguan") == null || request.getParameter("jiguan") == "") ? null : request.getParameter("jiguan");
        //用户数组与年龄一样需要判空否则如下的for循环会报空指针错误
        String[] aihao = request.getParameterValues("aihao") == null ? null : request.getParameterValues("aihao");
        String Aihao = "";
        if (aihao != null) {
            for (String s : aihao) {
                Aihao += s + ",";
            }
            Aihao = Aihao.substring(0, Aihao.length() - 1);
        }
        String u_imgPath = request.getParameter("u_img");
        //实体对象填充数据
        YzUsers u = new YzUsers();
        u.setId(user_id);
        if (uname != null) u.setUsername(uname);
        if (name != null) u.setRealname(name);
        if (password != null) u.setPassword(password);
        if (mobile != null) u.setMobile(mobile);
        if (aGe) u.setAge(age);
        if (address != null) u.setAddress(address);
        if (qq != null) u.setQq(qq);
        if (wechat != null) u.setWechat(wechat);
        if (email != null) u.setEmail(email);
        if (sex != null) u.setSex(sex);
        if (aihao != null) u.setHobby(Aihao);
        if (jiguan != null) u.setDerive(jiguan);
        if (u_imgPath != null) u.setU_img(u_imgPath);
        int result = us.updateUser(u);
        if (result > 0) {
            statusCode = 1;
            msg = "信息修改成功";
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //删除用户
    @RequestMapping(value = "user/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject deleteUser(@RequestParam("id") String user_id) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "用户注销失败";
        int result = us.deleteUser(user_id);
        if (result > 0) {
            statusCode = 1;
            msg = "用户注销成功";
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //查询用户（分页）
    @RequestMapping(value = "user/page-ulist", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String queryAllUsers(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "未获取到任何信息";
        Page<YzUsers> p = us.queryAllUsers(pageNum, pageSize);
        if (p != null) {
            json.put("page", p);
            statusCode = 1;
            msg = "获得用户信息列表";
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        //过滤掉子元素中的数组
        JSONFilter[] jfs = {
                new JSONFilter(YzUsers.class, "yzMerch", "yzMerchUserOrders"),
                new JSONFilter(YzStatus.class, "yzUserses")
        };
        return JSONObject.toJSONString(json, jfs).replace("page", "UserPage");
    }

    //批量插入用户  //get该技能之后可练习写购物车下单
    @RequestMapping(value = "user/batch-add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject InsertUserList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "批量添加失败";
        String BatchUser_status = request.getParameter("status") == null ? null : request.getParameter("status");
        Integer status = 12;//如果没有特定设置身份，默认12（大众会员）
        if (BatchUser_status != null) status = Integer.parseInt(BatchUser_status);
        List<Map<String, String>> userlist = null;
        String checkcode = "";
        try {
            checkcode = (String) map.get("checkcode");
            if (checkcode.equals("ab9e8")) {
                userlist = (List<Map<String, String>>) map.get("userlist");
                int AffectLine = us.BatchInsertUsers(userlist, status);
                if (AffectLine > 0) {
                    statusCode = 1;
                    msg = "批量添加成功";
                }
            } else {
                statusCode = -3;
                msg = "你没有授权码调用该接口";
            }
        } catch (Exception e) {
            statusCode = -2;
            msg = "请求参数格式不正确";
        }
        json.put("msg", msg);
        json.put("statusCode", statusCode);
        return json;
    }

    //批量查询用户List<user_id>
    @RequestMapping(value = "user/batch-find", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject BatchFind(@RequestParam(value = "uid", required = false) String... usernameS) {
        JSONObject json = new JSONObject();
        String msg = "查询失败";
        int statusCode = -1;
        List<String> list = null;
        if (usernameS != null && usernameS.length > 0) {
            list = new ArrayList<>();
            for (String id : usernameS)
                list.add(id);
            List<YzUsers> ulist = us.BatchFind(list);
            if (ulist.size() > 0) {
                statusCode = 1;
                msg = "查询成功";
                JSONArray arrs = new JSONArray();
                for (YzUsers uu : ulist)
                    arrs.add(uu);
                json.put("userList", arrs);
            }
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    //启动线程批量生成测试数据
    @RequestMapping(value = "user/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject ThreadTest(HttpServletRequest request, @RequestParam("Authorization") String code) {
        JSONObject json = null;
        boolean permission = (code == null || code == "") ? false : ("1999".equals(code) ? true : false);
        if (!permission) {
            json = new JSONObject();
            String msg = "授权码无效";
            int statusCode = -1;
            json.put("statusCode", statusCode);
            json.put("msg", msg);
        } else {
            json = us.ThreadTest(request);
        }
        return json;
    }

    private Color getRandomColor() {
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }

    @RequestMapping(value = "/CheckCode", method = RequestMethod.GET)
    public void checkCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        BufferedImage image = new BufferedImage(90, 30, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.yellow);
        graphics.fillRect(0, 0, 90, 30);
        for (int i = 0; i < 5; i++) {
            graphics.setColor(getRandomColor());
            int x1 = random.nextInt(90);
            int y1 = random.nextInt(30);
            int x2 = random.nextInt(90);
            int y2 = random.nextInt(30);
            graphics.drawLine(x1, y1, x2, y2);
        }
        char[] arrays = {'A', 'B', 'b', 'D', 'E', 'e'};
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(arrays.length);
            builder.append(arrays[index]);
        }
        for (int i = 0; i < builder.toString().length(); i++) {
            graphics.setColor(getRandomColor());
            char item = builder.toString().charAt(i);
            graphics.drawString(item + "", 10 + (i * 20), 15);
        }
        request.getSession(false).setAttribute("checkCode", builder.toString());
        ImageIO.write(image, "png", response.getOutputStream());
    }

}
